package sgi.client;

import java.io.IOException;
import java.util.Iterator;

import sgi.details_new.AccountInfoDetails;
import sgi.message.MessageHistory;
import sgi.message.MessageViewInfo;
import sgi.misc.History;

import sgi.user.User;

public class SGIAccountInfoController extends SGIController {
	public static SGIAccountInfoController accountInfo;
	public static SGIAccountInfoUI accountInfoUI;
	private static User user;
	
	
	/** create controller */
	public static SGIAccountInfoController create(User user) throws IOException
	{
		if(SGIAccountInfoController.accountInfo == null)
		{
			SGIAccountInfoController.accountInfo = new SGIAccountInfoController(user);
			accountInfoUI.setSGIAccountInfoController(SGIAccountInfoController.accountInfo);
		}
		SGIAccountInfoController.accountInfoUI.setVisible(true);
		return accountInfo;
	}
	/** constructor */
	private SGIAccountInfoController(User user) 
	{
		SGIAccountInfoController.accountInfoUI = new SGIAccountInfoUI(user);
		SGIAccountInfoController.user = new User(user);  
	}
	/** message for viewing info */
	public void ViewInfo(User user)
	{
		MessageViewInfo msg = new MessageViewInfo(user);
		sendViewInfo(msg);
	}
	/** sending message */
	private void sendViewInfo(MessageViewInfo msg)
	{
		try {
			(SGIClientConnectionController.createConnection()).handleMessageFromClientUI(msg);
		} catch  (IOException e) {e.printStackTrace();}
	}
	/** terminating ui */
	public static void terminate()
	{
		SGIAccountInfoController.accountInfoUI.setVisible(false);
		SGIAccountInfoController.accountInfoUI=null;
		SGIAccountInfoController.accountInfo=null;
		
	}
	
	public void getHistory()
	{
		MessageHistory msg = new MessageHistory();
		try {
			SGIClientConnectionController.createConnection().handleMessageFromClientUI(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/** handle message to get info */
	void handleMessage(Object msg) {
		if(msg instanceof MessageViewInfo)
		{
			Iterator<AccountInfoDetails> iterator = (((MessageViewInfo)msg).getAccountInfo()).iterator();
			SGIAccountInfoController.accountInfoUI.addAccountInfo(iterator.next());
		}
		if(msg instanceof MessageHistory)
		{
			Iterator<History> it = ((MessageHistory)msg).getPurchaseHistory().iterator();
			History cont;
		
			while(it.hasNext())
			{
				cont = it.next();
				accountInfoUI.addRowPurchaseHistory(cont.Description, cont.Time);
			}
			
			it = ((MessageHistory)msg).getSearchHistory().iterator();
			
			while(it.hasNext())
			{
				cont = it.next();
				accountInfoUI.addRowSearchHistory(cont.Description, cont.Time);
			}
		}

	}
	/** get ui */
	public static SGIAccountInfoUI getUI()
	{
		return accountInfoUI;
	}

}
